/**
 *
 * 用户注册接口
 *
 */
const rootPath = '../../../';
const router = require('express').Router();
const baseTool = require(rootPath + 'common/base-tool');
const tips = require(rootPath + 'common/tips');
const log = require(rootPath + 'common/log')
const CURD = require(rootPath + 'compontents/DB/CURDClass')
const RSA = require(rootPath + 'common/RSAClass');
const baseRole = require(rootPath + 'common/base-role')
const md5 = require('md5-node');
const crypto = require('crypto');

router.post('/register', async (req, res, next) => {
    log.api('user api register');

    const r = req.body;
    // const password2 = r.pwd2;
    const password = r.pwd;
    const uname = r.uname;
    console.log(r)

    if (!uname) {
        console.log(tips.uname.emport);
        res.json({
            code: tips.uname.emptyCode,
            msg: tips.uname.emport
        })
        return;
    }
    if (!baseTool.verifyName(uname)) {
        console.log(tips.uname.format);
        res.json({
            code: tips.uname.formatCode,
            msg: tips.uname.format
        })
        return;
    }
    if (!password) {
        console.log(tips.pwd.emport);
        res.json({
            code: tips.pwd.emptyCode,
            msg: tips.pwd.emport
        })
        return;
    }
    if (!baseTool.verifyPwd(password)) {
        res.json({
            code: tips.pwd.formatCode,
            msg: tips.pwd.format
        })
        return;
    }

    /**
     * =======================
     *   查询用户是否已存在
     * =======================
     */
    const has_user = await CURD.select({
        fields:'id',
        table:`user`,
        where: [
            {
                wfield: 'username',
                wvalue: uname
            },
            {
                wfield: 'password',
                wvalue: md5(password)
            }
        ]
    })
    // console.log(has_user.length)
    if (has_user.length) {
        res.json({
            code: tips.register.failCode,
            msg: tips.register.fail
        })
        return;
    }

    /**
     * =======================
     *   创建用户
     * =======================
     */
    const ctime = Math.round(new Date().getTime() / 1000);
    const token = await new RSA().encrypt(ctime);
    const uid = `XHPX${ctime}`;
    const register_rows = await CURD.insert({
        table: `user`,
        fields: 'uid, username, password, ctime, token',
        values: `${uid}, ${uname}, ${md5(password)}, ${ctime}, ${token}`
    });

    // 用户创建成功
    if ( register_rows.affectedRows == 1 ) {
        const t = register_rows.insertId +'_XHPX_'+ token.toString();
        // 公钥加密
        const publicKey = await new RSA().encrypt(t);

        //创建cookie对象
        res.cookie('uid', uid, {signed: false, maxAge: global.COOKIE_TIME});
        res.cookie('xhtk', publicKey, {signed: false, httpOnly: true, maxAge: global.COOKIE_TIME});

        // 将角色添加到在线玩家列表
        baseRole.add_online(uid);

        res.json({
            code: tips.successCode,
            msg: tips.success,
            status: -1
        })
    } else {
        console.log(tips.register.fail)
        res.json({
            code: tips.register.failCode,
            msg: tips.register.fail
        })
    }
});

module.exports = router;